<template>
  <div class="house-management-container">
    <div class="person-container">
      <LeftMenu />
      <div class="house-management-content">
        <el-card>
          <div class="management-header">
            <ManagementTitle>
              <template #title>房源管理</template>
            </ManagementTitle>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增房源
            </el-button>
          </div>

          <!-- 搜索区域 -->
          <div class="house-search">
            <div class="search-row">
              <el-input
                v-model="searchForm.title"
                placeholder="请输入房源标题"
                style="width: 200px; margin-right: 12px"
                clearable
              />
              <el-select
                v-model="searchForm.countyId"
                placeholder="选择区域"
                style="width: 150px; margin-right: 12px"
                clearable
              >
                <el-option
                  v-for="county in countyList"
                  :key="county.id"
                  :label="county.name"
                  :value="county.id"
                />
              </el-select>
              <el-select
                v-model="searchForm.rentalType"
                placeholder="出租类型"
                style="width: 120px; margin-right: 12px"
                clearable
              >
                <el-option label="整租" :value="1" />
                <el-option label="分租" :value="2" />
              </el-select>
              <el-select
                v-model="searchForm.state"
                placeholder="房源状态"
                style="width: 150px; margin-right: 12px"
                clearable
              >
                <el-option label="未审核" :value="0" />
                <el-option label="一级审核中" :value="1" />
                <el-option label="二级审核中" :value="2" />
                <el-option label="三级审核中" :value="3" />
                <el-option label="已上架" :value="4" />
                <el-option label="已出租" :value="5" />
                <el-option label="已下架" :value="6" />
                <el-option label="审核失败" :value="7" />
              </el-select>
              <div class="rent-range-container">
                <span class="range-label">租金范围：</span>
                <el-input-number
                  v-model="searchForm.rentMin"
                  placeholder="最低租金"
                  :min="0"
                  :max="99999"
                  style="width: 120px; margin-right: 8px"
                  controls-position="right"
                />
                <span class="range-separator">-</span>
                <el-input-number
                  v-model="searchForm.rentMax"
                  placeholder="最高租金"
                  :min="0"
                  :max="99999"
                  style="width: 120px; margin-right: 12px"
                  controls-position="right"
                />
              </div>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </div>
          
          <!-- 房源卡片列表 -->
          <div class="house-cards-container" style="margin-top: 16px;">
            <div v-if="loading" class="loading-state">
              <el-skeleton :rows="3" animated />
            </div>

            <div v-else-if="houseList.length > 0" class="house-cards">

              <div
                v-for="house in houseList"
                :key="house.id"
                class="house-card"
              >
                  <!-- 左侧图片 -->
                  <div class="house-image">
                    <img
                      :src="getFirstImage(house.imageUrls || '') || getDefaultImage()"
                      :alt="house.title"
                      class="house-img"
                      @error="handleImageError"
                    />
                    <div class="house-status">
                      <span class="status-tag" :class="getStatusClass(house.state)">
                        {{ getStatusText(house.state) }}
                      </span>
                    </div>
                    <div class="rental-type-tag">
                      <span class="rental-tag" :class="house.rentalType === 1 ? 'whole-rent' : 'shared-rent'">
                        {{ house.rentalType === 1 ? '整租' : '分租' }}
                      </span>
                    </div>
                  </div>

                  <!-- 中间信息 -->
                  <div class="house-info">
                    <div class="house-card-header">
                      <h3 class="house-title">{{ house.name || house.title || '房源' + house.id }}</h3>
                      <div class="house-right">
                        <div class="house-price">
                          <span class="price-amount">{{ formatMoney(house.rent || house.price || 0) }}</span>
                          <span class="price-unit">元/月</span>
                        </div>
                      </div>
                    </div>

                    <div class="house-details">
                      <div class="detail-item">
                        <span class="detail-label">房源编号：</span>
                        <span class="detail-value">{{ house.houseCode || '暂无' }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="detail-label">房屋面积：</span>
                        <span class="detail-value">{{ house.area || '暂无' }}㎡</span>
                      </div>
                      <div class="detail-item">
                        <span class="detail-label">户型配置：</span>
                        <span class="detail-value">{{ house.typeNum || '暂无' }}室{{ house.type || '暂无' }}</span>
                      </div>
                      <div class="detail-item">
                        <span class="detail-label">详细地址：</span>
                        <span class="detail-value">{{ house.address || '暂无' }}</span>
                      </div>
                      <div class="detail-item" v-if="house.listTime">
                        <span class="detail-label">挂牌时间：</span>
                        <span class="detail-value">{{ formatDate(house.listTime) }}</span>
                      </div>
                    </div>

                    <div class="house-actions">
                      <el-button type="primary" @click="handleViewDetails(house)">
                        详情
                      </el-button>
                      <el-button @click="handleEdit(house)">
                        编辑
                      </el-button>
                      <el-button type="danger" @click="handleDeleteHouse(house)">
                        删除
                      </el-button>
                      <el-button type="warning" @click="handleOffline(house)">
                        下架
                      </el-button>
                    </div>
                  </div>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="empty-state">
              <el-empty description="暂无房源数据">
                <el-button type="primary" @click="handleAdd">添加房源</el-button>
              </el-empty>
            </div>
          </div>
          
          <!-- 分页 -->
          <div class="table-pagination">
            <el-pagination
              background
              layout="total, prev, pager, next"
              :total="total"
              :page-size="pageSize"
              :current-page="currentPage"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 房源管理抽屉 -->
    <el-drawer
      :title="dialogTitle"
      v-model="dialogVisible"
      direction="rtl"
      size="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房源标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入房源标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="户号" prop="num">
              <el-input-number
                v-model="formData.num"
                :min="1"
                placeholder="户号"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="租金" prop="rent">
              <el-input-number
                v-model="formData.rent"
                :min="0"
                :precision="2"
                placeholder="租金"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="几居室" prop="typeNum">
              <el-input-number
                v-model="formData.typeNum"
                :min="0"
                placeholder="几居室"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房屋面积" prop="area">
              <el-input-number
                v-model="formData.area"
                :min="0"
                :precision="2"
                placeholder="房屋面积"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="户型" prop="type">
              <el-input v-model="formData.type" placeholder="请输入户型" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房源用途" prop="houseUse">
              <el-select v-model="formData.houseUse" placeholder="请选择房源用途" style="width: 100%">
                <el-option label="住宅" :value="1" />
                <el-option label="公寓" :value="2" />
                <el-option label="办公" :value="3" />
                <el-option label="商铺" :value="4" />
                <el-option label="写字楼" :value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="朝向" prop="orientation">
              <el-select v-model="formData.orientation" placeholder="请选择朝向" style="width: 100%">
                <el-option label="东" :value="1" />
                <el-option label="南" :value="2" />
                <el-option label="西" :value="3" />
                <el-option label="北" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="装修类型" prop="decoration">
              <el-select v-model="formData.decoration" placeholder="请选择装修类型" style="width: 100%">
                <el-option label="毛坯" :value="1" />
                <el-option label="简装" :value="2" />
                <el-option label="精装" :value="3" />
                <el-option label="豪装" :value="4" />
                <el-option label="其他" :value="5" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出租类型" prop="rentalType">
              <el-select v-model="formData.rentalType" placeholder="请选择出租类型" style="width: 100%">
                <el-option label="整租" :value="1" />
                <el-option label="分租" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="房源状态" prop="state">
              <el-select v-model="formData.state" placeholder="请选择房源状态" style="width: 100%">
                <el-option label="未审核" :value="0" />
                <el-option label="一级审核中" :value="1" />
                <el-option label="二级审核中" :value="2" />
                <el-option label="三级审核中" :value="3" />
                <el-option label="已上架" :value="4" />
                <el-option label="已出租" :value="5" />
                <el-option label="已下架" :value="6" />
                <el-option label="审核失败" :value="7" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付类型" prop="payType">
              <el-select v-model="formData.payType" placeholder="请选择支付类型" style="width: 100%">
                <el-option label="付一押一" :value="1" />
                <el-option label="付一押二" :value="2" />
                <el-option label="付一押三" :value="3" />
                <el-option label="付二押一" :value="4" />
                <el-option label="付三押一" :value="5" />
                <el-option label="付三押二" :value="6" />
                <el-option label="月付" :value="7" />
                <el-option label="半年付" :value="8" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所在楼层" prop="floor">
              <el-select v-model="formData.floor" placeholder="请选择所在楼层" style="width: 100%">
                <el-option label="低层" :value="1" />
                <el-option label="中层" :value="2" />
                <el-option label="高层" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="房源核验码" prop="houseCode">
              <el-input v-model="formData.houseCode" placeholder="请输入房源核验码" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区域" prop="region">
              <el-select v-model="formData.region" placeholder="请选择区域" style="width: 100%">
                <el-option
                  v-for="county in allCounties"
                  :key="county.id"
                  :label="county.name"
                  :value="county.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input v-model="formData.address" placeholder="请输入详细地址" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="配套设施" prop="facilities">
              <div class="facility-selection">
                <el-checkbox-group v-model="selectedFormFacilityIds" @change="onFormFacilityChange">
                  <el-checkbox
                    v-for="facility in allFacilities"
                    :key="facility.id"
                    :label="facility.id"
                    class="facility-checkbox"
                  >
                    {{ facility.name }}
                  </el-checkbox>
                </el-checkbox-group>
                <div class="facility-preview" v-if="formData.facilities">
                  <small class="text-muted">存储格式预览：{{ formData.facilities }}</small>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="房东要求" prop="need">
              <el-input
                v-model="formData.need"
                type="textarea"
                :rows="2"
                placeholder="请输入房东要求"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="房源描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                :rows="3"
                placeholder="请输入房源描述"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="房源图片" prop="imageUrls">
              <div class="house-image-upload">
                <el-upload
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :file-list="formImageList"
                  :on-success="handleFormImageSuccess"
                  :on-remove="handleFormImageRemove"
                  :on-error="handleFormImageError"
                  :before-upload="beforeFormImageUpload"
                  list-type="picture-card"
                  accept="image/*"
                  :limit="10"
                  :disabled="formUploadLoading"
                >
                  <el-icon v-if="!formUploadLoading"><Plus /></el-icon>
                  <el-icon v-else class="is-loading"><Loading /></el-icon>
                </el-upload>
                <div class="upload-tip">
                  <small class="text-muted">支持jpg、png、gif等格式，最多上传10张图片，每张图片不超过5MB</small>
                </div>
                <div class="image-urls-preview" v-if="formData.imageUrls">
                  <small class="text-muted">存储格式：{{ formData.imageUrls }}</small>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="drawer-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '更新' : '保存' }}
          </el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 房源详情侧滑面板 -->
    <el-drawer
      v-model="showHouseDetailDrawer"
      title="房源详情"
      direction="rtl"
      size="500px"
      :before-close="handleDrawerClose"
    >
      <div v-if="currentHouse" class="house-detail-content">
        <el-form :model="houseDetailForm" label-width="100px" ref="houseDetailFormRef">
          <el-form-item label="房号">
            <el-input v-model="houseDetailForm.num" disabled />
          </el-form-item>

          <el-form-item label="户型">
            <el-input v-model="houseDetailForm.type" placeholder="请输入户型，如：三室两厅一卫" />
          </el-form-item>

          <el-form-item label="面积(㎡)">
            <el-input-number v-model="houseDetailForm.area" :min="0" style="width: 100%" />
          </el-form-item>

          <el-form-item label="租金(元/月)">
            <el-input-number v-model="houseDetailForm.rent" :min="0" style="width: 100%" />
          </el-form-item>

          <el-form-item label="房屋用途">
            <el-select v-model="houseDetailForm.houseUse" style="width: 100%">
              <el-option label="住宅" :value="1" />
              <el-option label="公寓" :value="2" />
              <el-option label="办公" :value="3" />
              <el-option label="商铺" :value="4" />
              <el-option label="写字楼" :value="5" />
            </el-select>
          </el-form-item>

          <el-form-item label="租赁类型">
            <el-select v-model="houseDetailForm.rentalType" style="width: 100%">
              <el-option label="整租" :value="1" />
              <el-option label="分租" :value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="房源权属">
            <el-select v-model="houseDetailForm.ownershipType" style="width: 100%">
              <el-option label="企业" :value="0" />
              <el-option label="个人" :value="1" />
              <el-option label="居间" :value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="装修类型">
            <el-select v-model="houseDetailForm.decoration" style="width: 100%">
              <el-option label="毛坯" :value="1" />
              <el-option label="简装" :value="2" />
              <el-option label="精装" :value="3" />
              <el-option label="豪装" :value="4" />
              <el-option label="其他" :value="5" />
            </el-select>
          </el-form-item>

          <el-form-item label="支付类型">
            <el-select v-model="houseDetailForm.payType" style="width: 100%">
              <el-option label="付一押一" :value="1" />
              <el-option label="付一押二" :value="2" />
              <el-option label="付一押三" :value="3" />
              <el-option label="付二押一" :value="4" />
              <el-option label="付三押一" :value="5" />
              <el-option label="付三押二" :value="6" />
              <el-option label="月付" :value="7" />
              <el-option label="半年付" :value="8" />
            </el-select>
          </el-form-item>

          <el-form-item label="朝向">
            <el-select v-model="houseDetailForm.orientation" style="width: 100%">
              <el-option label="东" :value="1" />
              <el-option label="南" :value="2" />
              <el-option label="西" :value="3" />
              <el-option label="北" :value="4" />
            </el-select>
          </el-form-item>

          <el-form-item label="所在楼层">
            <el-select v-model="houseDetailForm.floor" style="width: 100%">
              <el-option label="低层" :value="1" />
              <el-option label="中层" :value="2" />
              <el-option label="高层" :value="3" />
            </el-select>
          </el-form-item>

          <el-form-item label="房屋状态">
            <el-tag :type="getStatusTagType(houseDetailForm.state)">
              {{ getStatusText(houseDetailForm.state) }}
            </el-tag>
          </el-form-item>

          <el-form-item label="房屋标题">
            <el-input v-model="houseDetailForm.title" type="textarea" :rows="2" />
          </el-form-item>

          <el-form-item label="几居室">
            <el-input-number v-model="houseDetailForm.typeNum" :min="0" style="width: 100%" />
          </el-form-item>

          <el-form-item label="区域">
            <el-select v-model="houseDetailForm.region" placeholder="请选择区域" style="width: 100%">
              <el-option
                v-for="county in allCounties"
                :key="county.id"
                :label="county.name"
                :value="county.name"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="详细地址">
            <el-input v-model="houseDetailForm.address" />
          </el-form-item>

          <el-form-item label="配套设施">
            <div class="facility-selection">
              <el-checkbox-group v-model="selectedFacilityIds" @change="onFacilityChange">
                <el-checkbox
                  v-for="facility in allFacilities"
                  :key="facility.id"
                  :label="facility.id"
                  class="facility-checkbox"
                >
                  {{ facility.name }}
                </el-checkbox>
              </el-checkbox-group>
              <div class="facility-preview" v-if="houseDetailForm.facilities">
                <small class="text-muted">存储格式预览：{{ houseDetailForm.facilities }}</small>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="房东要求">
            <el-input v-model="houseDetailForm.need" type="textarea" :rows="2" />
          </el-form-item>

          <el-form-item label="房源描述">
            <el-input v-model="houseDetailForm.description" type="textarea" :rows="3" />
          </el-form-item>

          <el-form-item label="房源图片">
            <div class="house-image-upload">
              <el-upload
                :action="uploadUrl"
                :headers="uploadHeaders"
                :file-list="houseImageList"
                :on-success="handleHouseImageSuccess"
                :on-remove="handleHouseImageRemove"
                :on-error="handleHouseImageError"
                :before-upload="beforeHouseImageUpload"
                list-type="picture-card"
                accept="image/*"
                :limit="10"
                :disabled="uploadLoading"
              >
                <el-icon v-if="!uploadLoading"><Plus /></el-icon>
                <el-icon v-else class="is-loading"><Loading /></el-icon>
              </el-upload>
              <div class="upload-tip">
                <small class="text-muted">支持jpg、png、gif等格式，最多上传10张图片，每张图片不超过5MB</small>
              </div>
              <div class="image-urls-preview" v-if="houseDetailForm.imageUrls">
                <small class="text-muted">存储格式：{{ houseDetailForm.imageUrls }}</small>
              </div>
            </div>
          </el-form-item>
        </el-form>

        <div class="drawer-footer">
          <el-button @click="handleDrawerClose">取消</el-button>
          <el-button type="primary" @click="saveHouseDetail" :loading="saveLoading">保存修改</el-button>
        </div>
      </div>
    </el-drawer>


  </div>
</template>

<script setup lang="ts">
import LeftMenu from "@/user/LeftMenu.vue";
import { ref, reactive, onMounted } from "vue";
import ManagementTitle from "@/components/ManagementTitle.vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Loading } from '@element-plus/icons-vue';
import http from '@/utils/http';
import axios from 'axios';
import type { House, County, SearchForm, HouseDetailForm, Facility } from "@/types/formRulesInterface";

// 响应式数据
const loading = ref(false);
const houseList = ref<House[]>([]);
const countyList = ref<County[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = 10;

// 房源详情侧滑面板相关
const showHouseDetailDrawer = ref(false);
const currentHouse = ref<House | null>(null);
const saveLoading = ref(false);
const houseDetailFormRef = ref();
const houseDetailForm = ref<HouseDetailForm>({} as HouseDetailForm);
const buildingTypes = ref<any[]>([]);
const allFacilities = ref<Facility[]>([]);
const selectedFacilityIds = ref<number[]>([]);
const houseImageList = ref<any[]>([]);
const uploadLoading = ref(false);
const allCounties = ref<County[]>([]);

// 新增表单相关
const selectedFormFacilityIds = ref<number[]>([]);
const formImageList = ref<any[]>([]);
const formUploadLoading = ref(false);

// 搜索表单
const searchForm = reactive<SearchForm>({
  title: '',
  countyId: '',
  rentalType: '',
  state: '',
  rentMin: null,
  rentMax: null
});

// 上传相关
const uploadUrl = ref('http://127.0.0.1:8080/oss/file/upload');
const uploadHeaders = ref({});



// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const isEdit = ref(false);
const submitLoading = ref(false);
const formRef = ref();

// 表单数据
const formData = reactive({
  id: null,
  userId: null,
  num: null,
  title: '',
  rent: null,
  payType: null,
  type: '',
  area: null,
  decoration: null,
  region: '',
  floor: null,
  houseUse: null,
  orientation: null,
  listTime: null,
  houseCode: '',
  facilities: '',
  need: '',
  description: '',
  imageUrls: '',
  sourceId: null,
  state: 0,
  rentalType: null,
  source: '',
  ownershipType: null,
  address: '',
  typeNum: null
});

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入房源标题', trigger: 'blur' }
  ],
  num: [
    { required: true, message: '请输入户号', trigger: 'blur' }
  ],
  rent: [
    { required: true, message: '请输入租金', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '请输入房屋面积', trigger: 'blur' }
  ],
  rentalType: [
    { required: true, message: '请选择出租类型', trigger: 'change' }
  ],
  houseUse: [
    { required: true, message: '请选择房源用途', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
};

// 获取房源列表
const getHouseList = async () => {
  try {
    loading.value = true
    const params: any = {
      page: currentPage.value,
      limit: pageSize
    }

    // 添加搜索条件
    if (searchForm.title) params.title = searchForm.title
    if (searchForm.countyId) params.countyId = searchForm.countyId
    if (searchForm.rentalType) params.rentalType = searchForm.rentalType
    if (searchForm.state !== '') params.state = searchForm.state
    if (searchForm.rentMin) params.rentMin = searchForm.rentMin
    if (searchForm.rentMax) params.rentMax = searchForm.rentMax

    console.log('发送房源查询请求，参数:', params)
    const response = await http.get('/rental/areaplothouse/page/admin', { params })

    console.log('后端返回的完整响应:', response.data)

    // 响应拦截器已经处理了code判断，直接使用数据
    try {
      const list = response.data.list || []
      const totalCount = response.data.total || 0

      console.log('准备设置的数据 - list:', list, 'total:', totalCount)

      houseList.value = list
      total.value = totalCount

      console.log('设置后的houseList:', houseList.value)
      console.log('设置后的total:', total.value)
      console.log('数据设置成功')
    } catch (dataError) {
      console.error('数据设置失败:', dataError)
      throw dataError
    }
  } catch (error: any) {
    console.error('获取房源列表失败:', error)
    console.error('错误详情:', error.message)
    console.error('错误堆栈:', error.stack)
    ElMessage.error('获取房源列表失败：' + (error.message || '请检查网络连接'))
  } finally {
    loading.value = false
  }
}

// 获取区域列表
const getCountyList = async () => {
  try {
    const response = await http.get('/rental/areacounty/getAllCounty')
    if (response.data.code === 0) {
      countyList.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取区域列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getHouseList()
}

// 重置
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    (searchForm as any)[key] = key.includes('Min') || key.includes('Max') ? null : ''
  })
  currentPage.value = 1
  getHouseList()
}

// 分页
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  getHouseList()
}







// 操作方法


const handleAdd = () => {
  dialogTitle.value = '新增房源'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = async (house: any) => {
  dialogTitle.value = '编辑房源'
  isEdit.value = true

  // 填充表单数据
  Object.keys(formData).forEach(key => {
    if ((house as any)[key] !== undefined) {
      (formData as any)[key] = (house as any)[key]
    }
  })

  // 解析配套设施
  if (house.facilities) {
    selectedFormFacilityIds.value = await parseFacilitiesFromString(house.facilities)
  } else {
    selectedFormFacilityIds.value = []
  }

  // 加载图片列表
  updateFormImageList()

  dialogVisible.value = true
}

// 显示房源详情
const showHouseDetail = async (house: any) => {
  currentHouse.value = house
  houseDetailForm.value = { ...house }
  showHouseDetailDrawer.value = true

  // 获取楼栋户型列表
  await getBuildingTypes()

  // 解析配套设施
  if (house.facilities) {
    selectedFacilityIds.value = await parseFacilitiesFromString(house.facilities)
  } else {
    selectedFacilityIds.value = []
  }

  // 加载房源图片列表
  updateHouseImageList()
}

const handleDeleteHouse = async (house: any) => {
  try {
    await ElMessageBox.confirm('确定要删除此房源吗？删除后无法恢复！', '提示', {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await axios.delete('/rental/areaplothouse', {
      data: [house.id],
      headers: { 'Content-Type': 'application/json' }
    })

    if (response.data.code === 0) {
      ElMessage.success('房源删除成功')
      getHouseList()
    } else {
      ElMessage.error('房源删除失败：' + response.data.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('房源删除失败:', error)
      ElMessage.error('房源删除失败，请检查网络连接')
    }
  }
}

const handleViewDetails = (house: any) => {
  ElMessage.info('查看房源详情：' + house.title)
  // TODO: 跳转到房源详情页面
}

const handleOffline = async (house: any) => {
  try {
    await ElMessageBox.confirm('确定要下架此房源吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 更新房源状态为已下架(6)
    const response = await http.put(`/rental/areaplothouse/${house.id}`, {
      ...house,
      state: 6
    })

    if (response.data.code === 0) {
      ElMessage.success('房源下架成功')
      getHouseList()
    } else {
      ElMessage.error('房源下架失败：' + response.data.msg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('房源下架失败:', error)
      ElMessage.error('房源下架失败，请检查网络连接')
    }
  }
}

// 对话框操作
const handleDialogClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  Object.keys(formData).forEach(key => {
    if (typeof (formData as any)[key] === 'number') {
      (formData as any)[key] = null
    } else {
      (formData as any)[key] = key === 'state' ? 0 : ''
    }
  })
  // 重置新增表单相关数据
  selectedFormFacilityIds.value = []
  formImageList.value = []
  formUploadLoading.value = false
  formRef.value?.clearValidate()
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true

    // 准备提交数据
    const submitData = { ...formData }

    // 如果是新增房源，尝试获取当前用户信息
    if (!isEdit.value) {
      try {
        const userResponse = await axios.get('/sys/user/info')
        if (userResponse.data.code === 0 && userResponse.data.data) {
          (submitData as any).creator = userResponse.data.data.id
          console.log('设置创建者ID:', (submitData as any).creator)
        } else {
          // 如果无法获取用户信息，使用默认创建者ID
          (submitData as any).creator = '1067246875800000001'
          console.log('使用默认创建者ID:', (submitData as any).creator)
        }
      } catch (error) {
        console.warn('获取用户信息失败，使用默认创建者ID:', error);
        (submitData as any).creator = '1067246875800000001'
      }
    }

    let url, method
    if (isEdit.value) {
      // 修改房源
      url = `/rental/areaplothouse/${formData.id}`
      method = 'put'
    } else {
      // 新增房源
      url = '/rental/areaplothouse/create'
      method = 'post'
    }

    const response = await (axios as any)[method](url, submitData)

    if (response.data.code === 0) {
      ElMessage.success(isEdit.value ? '房源更新成功' : '房源创建成功')
      dialogVisible.value = false
      getHouseList()
    } else {
      ElMessage.error(response.data.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请检查网络连接')
  } finally {
    submitLoading.value = false
  }
}

// Drawer相关方法
const handleDrawerClose = () => {
  showHouseDetailDrawer.value = false
  currentHouse.value = null
  selectedFacilityIds.value = []
  houseImageList.value = []
}

const saveHouseDetail = async () => {
  try {
    saveLoading.value = true
    const response = await axios.put(`/rental/areaplothouse/${currentHouse.value?.id}`, houseDetailForm.value)

    if (response.data.code === 0) {
      ElMessage.success('房源信息更新成功')
      handleDrawerClose()
      getHouseList()
    } else {
      ElMessage.error(response.data.msg || '更新失败')
    }
  } catch (error) {
    console.error('保存房源详情失败:', error)
    ElMessage.error('保存失败，请检查网络连接')
  } finally {
    saveLoading.value = false
  }
}

// 工具方法
const getFirstImage = (imageUrls: string | string[] | undefined) => {
  if (!imageUrls) return null
  if (Array.isArray(imageUrls)) {
    return imageUrls[0] || null
  }
  if (typeof imageUrls === 'string' && imageUrls.trim()) {
    const urls = imageUrls.split(',')
    return urls[0]?.trim() || null
  }
  return null
}

const getDefaultImage = () => {
  // 使用本地默认图片或者base64图片，避免外部服务不可用
  return ''
}

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  // 避免无限重试，只设置一次默认图片
  if (!img.dataset.errorHandled) {
    img.dataset.errorHandled = 'true'
    img.src = getDefaultImage()
  }
}

const formatMoney = (amount: number) => {
  if (!amount) return '0'
  return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

const formatDate = (date: string | Date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleDateString('zh-CN')
}

// 状态处理方法
const getStatusText = (state: number) => {
  const statusMap: { [key: number]: string } = {
    0: '未审核',
    1: '一级审核中',
    2: '二级审核中',
    3: '三级审核中',
    4: '已上架',
    5: '已出租',
    6: '已下架',
    7: '审核失败'
  }
  return statusMap[state] || '未知状态'
}

const getStatusClass = (state: number) => {
  const classMap: { [key: number]: string } = {
    0: 'pending',     // 未审核 - 灰色
    1: 'reviewing',   // 一级审核中 - 蓝色
    2: 'reviewing',   // 二级审核中 - 蓝色
    3: 'reviewing',   // 三级审核中 - 蓝色
    4: 'active',      // 已上架 - 绿色
    5: 'rented',      // 已出租 - 紫色
    6: 'offline',     // 已下架 - 橙色
    7: 'rejected'     // 审核失败 - 红色
  }
  return classMap[state] || 'unknown'
}

// 获取状态标签类型
const getStatusTagType = (state: number) => {
  switch (state) {
    case 0: return 'info'    // 未审核
    case 1:
    case 2:
    case 3: return 'warning' // 审核中
    case 4: return 'success' // 已上架
    case 5: return 'success' // 已出租
    case 6: return 'info'    // 已下架
    case 7: return 'danger'  // 审核失败
    default: return 'info'
  }
}



// 获取楼栋户型列表
const getBuildingTypes = async () => {
  try {
    // 这里可以根据需要获取户型列表，暂时使用空数组
    buildingTypes.value = []
  } catch (error) {
    console.error('获取户型列表失败:', error)
  }
}

// 配套设施相关方法
const loadAllFacilities = async () => {
  try {
    const response = await axios.get('/rental/housefacility/all')
    if (response.data.code === 0) {
      allFacilities.value = response.data.data || []
      console.log('配套设施列表:', allFacilities.value)
    } else {
      ElMessage.error('获取配套设施列表失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('获取配套设施列表失败:', error)
    ElMessage.error('获取配套设施列表失败，请检查网络连接')
  }
}

const parseFacilitiesFromString = async (facilitiesStr: string) => {
  if (!facilitiesStr) return []

  try {
    const response = await axios.post(`/rental/areaplothouse/parseFacilities?facilitiesStr=${encodeURIComponent(facilitiesStr)}`)
    if (response.data.code === 0) {
      return response.data.data || []
    }
  } catch (error) {
    console.error('解析配套设施失败:', error)
  }
  return []
}

const convertFacilitiesToString = async (facilityIds: number[]) => {
  if (!facilityIds || facilityIds.length === 0) return ''

  try {
    const response = await axios.post('/rental/areaplothouse/convertFacilities', {
      facilityIds: facilityIds
    })
    if (response.data.code === 0) {
      return response.data.data || ''
    }
  } catch (error) {
    console.error('转换配套设施失败:', error)
  }
  return ''
}

const onFacilityChange = async () => {
  const facilitiesStr = await convertFacilitiesToString(selectedFacilityIds.value)
  houseDetailForm.value.facilities = facilitiesStr
}

// 新增表单配套设施处理
const onFormFacilityChange = async () => {
  const facilitiesStr = await convertFacilitiesToString(selectedFormFacilityIds.value)
  formData.facilities = facilitiesStr
}

// 图片上传相关方法
const parseImageUrls = (imageUrlsStr: string): string[] => {
  if (!imageUrlsStr) return []
  return imageUrlsStr.split(',').filter(url => url.trim())
}

const formatImageUrls = (urls: string[]): string => {
  return urls.filter(url => url.trim()).join(',')
}

const updateHouseImageList = () => {
  const urls = parseImageUrls(houseDetailForm.value.imageUrls || '')
  houseImageList.value = urls.map((url, index) => ({
    uid: index,
    name: `image-${index + 1}`,
    status: 'done',
    url: url
  }))
}

// 房源详情图片上传
const beforeHouseImageUpload = (file: any) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  uploadLoading.value = true
  return true
}

const handleHouseImageSuccess = (response: any, file: any) => {
  uploadLoading.value = false
  if (response.code === 0) {
    const currentUrls = parseImageUrls(houseDetailForm.value.imageUrls || '')
    // OSS接口返回的是UploadDTO对象，包含url字段
    currentUrls.push(response.data.url)
    houseDetailForm.value.imageUrls = formatImageUrls(currentUrls)
    updateHouseImageList()
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败：' + response.msg)
  }
}

const handleHouseImageRemove = (file: any) => {
  const currentUrls = parseImageUrls(houseDetailForm.value.imageUrls || '')
  const filteredUrls = currentUrls.filter(url => url !== file.url)
  houseDetailForm.value.imageUrls = formatImageUrls(filteredUrls)
  updateHouseImageList()
}

const handleHouseImageError = (error: any) => {
  uploadLoading.value = false
  ElMessage.error('图片上传失败，请重试')
  console.error('图片上传错误:', error)
}

// 新增表单图片上传处理
const updateFormImageList = () => {
  const urls = parseImageUrls(formData.imageUrls || '')
  formImageList.value = urls.map((url, index) => ({
    uid: index,
    name: `image-${index + 1}`,
    status: 'done',
    url: url
  }))
}

const beforeFormImageUpload = (file: any) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  formUploadLoading.value = true
  return true
}

const handleFormImageSuccess = (response: any, file: any) => {
  formUploadLoading.value = false
  if (response.code === 0) {
    const currentUrls = parseImageUrls(formData.imageUrls || '')
    currentUrls.push(response.data.url)
    formData.imageUrls = formatImageUrls(currentUrls)
    updateFormImageList()
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error('图片上传失败：' + response.msg)
  }
}

const handleFormImageRemove = (file: any) => {
  const currentUrls = parseImageUrls(formData.imageUrls || '')
  const filteredUrls = currentUrls.filter(url => url !== file.url)
  formData.imageUrls = formatImageUrls(filteredUrls)
  updateFormImageList()
}

const handleFormImageError = (error: any) => {
  formUploadLoading.value = false
  ElMessage.error('图片上传失败，请重试')
  console.error('新增表单图片上传错误:', error)
}

// 初始化
onMounted(() => {
  console.log('房源管理页面初始化')
  console.log('当前token:', localStorage.getItem('token') ? '存在' : '不存在')

  getCountyList()
  getHouseList()
  loadAllFacilities()
  loadAllCounties()
})

// 区域相关方法
const loadAllCounties = async () => {
  try {
    const response = await axios.get('/rental/areacounty/getAllCounty')
    if (response.data.code === 0) {
      allCounties.value = response.data.data || []
      console.log('区域列表:', allCounties.value)
    } else {
      ElMessage.error('获取区域列表失败：' + response.data.msg)
    }
  } catch (error) {
    console.error('获取区域列表失败:', error)
    ElMessage.error('获取区域列表失败，请检查网络连接')
  }
}
</script>

<style scoped>
.house-management-container {
  display: flex;
  flex-direction: column;
}

.person-container {
  max-width: 1290px;
  width: 100%;
  margin: 20px auto;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  box-sizing: border-box;
  padding: 0 16px;
}

.house-management-content {
  margin-left: 10px;
  flex: 1 1 0;
  min-width: 0;
  width: 100%;
  max-width: 100%;
}

.house-search {
  margin-bottom: 16px;
}

.search-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.rent-range-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.range-label {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

.range-separator {
  color: #909399;
  margin: 0 4px;
}

.table-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 房源卡片样式 */
.house-cards-container {
  min-height: 400px;
}

.house-cards {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.house-card {
  display: flex;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.3s ease;
  border: 1px solid #e4e7ed;
  height: 200px;
}

.house-card:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.house-image {
  position: relative;
  width: 320px;
  height: 200px;
  flex-shrink: 0;
  overflow: hidden;
  background: #f5f5f5;
}

.house-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 12px 0 0 12px;
  display: block;
  vertical-align: top;
  margin: 0;
  padding: 0;
}

.house-status {
  position: absolute;
  top: 12px;
  left: 12px;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.status-tag.pending {
  background: #909399;
}

.status-tag.reviewing {
  background: #409eff;
}

.status-tag.active {
  background: #67c23a;
}

.status-tag.rented {
  background: #722ed1;
}

.status-tag.offline {
  background: #e6a23c;
}

.status-tag.rejected {
  background: #f56c6c;
}

.status-tag.unknown {
  background: #c0c4cc;
}

.rental-type-tag {
  position: absolute;
  top: 12px;
  right: 12px;
}

.rental-tag {
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  color: white;
}

.rental-tag.whole-rent {
  background: #409eff;
}

.rental-tag.shared-rent {
  background: #e6a23c;
}

.house-info {
  flex: 1;
  padding: 8px 12px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.management-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.house-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 0px;
}

.house-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.house-title {
  font-size: 26px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 4px 0;
  line-height: 1.3;
}

.house-price {
  text-align: right;
}

.price-amount {
  font-size: 24px;
  font-weight: 600;
  color: #f56c6c;
}

.price-unit {
  font-size: 16px;
  color: #909399;
  margin-left: 4px;
}

.house-details {
  flex: 1;
  margin-bottom: 2px;
  margin-top: 2px;
}

.detail-item {
  display: flex;
  margin-bottom: 3px;
  font-size: 16px;
  line-height: 1.4;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-label {
  color: #909399;
  min-width: 75px;
  flex-shrink: 0;
  font-size: 16px;
}

.detail-value {
  color: #606266;
  flex: 1;
  font-size: 16px;
  font-weight: 500;
}

.house-actions {
  display: flex;
  gap: 10px;
  margin-top: 4px;
  padding-top: 4px;
}

.loading-state {
  padding: 20px;
}

.empty-state {
  padding: 60px 20px;
  text-align: center;
}

/* 房源详情侧滑面板样式 */
.house-detail-content {
  padding: 20px;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}

/* 配套设施样式 */
.facility-selection {
  width: 100%;
}

.facility-checkbox {
  display: inline-block;
  margin: 4px 8px 4px 0;
  white-space: nowrap;
}

:deep(.facility-checkbox .el-checkbox__label) {
  font-size: 13px;
  padding-left: 6px;
}

.facility-preview {
  margin-top: 8px;
  padding: 6px 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

/* 图片上传样式 */
.house-image-upload {
  width: 100%;
}

.upload-tip {
  margin-top: 8px;
}

.image-urls-preview {
  margin-top: 8px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
  word-break: break-all;
}

/* 响应式设计 */
@media (max-width: 900px) {
  .person-container {
    flex-direction: column;
    align-items: stretch;
    padding: 0 4px;
  }

  .house-management-content {
    margin-left: 0;
    width: 100%;
    max-width: 100%;
  }

  .house-card {
    flex-direction: column;
  }

  .house-image {
    width: 100%;
    height: 200px;
  }

  .house-card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .house-price {
    text-align: left;
    margin-top: 8px;
  }

  .house-actions {
    flex-wrap: wrap;
    justify-content: center;
  }

  .search-row {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .house-search .el-input,
  .house-search .el-select,
  .house-search .el-input-number {
    width: 100% !important;
  }
}

@media (max-width: 768px) {
  .rent-range-container {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }

  .range-label {
    align-self: flex-start;
  }
}
</style>
